var bmap_edit_branch, bmap_new_branch;
$(function () {
    var form_new_branch = window.form_new_branch;
    var form_edit_branch = window.form_edit_branch;


    $(function () {
        $('[data-toggle="branch-pic-popover"]').popover({
            animation: true,
            html: true,
            trigger: "hover",
            content: function () {
                return "<img class='img-branch-cover' src='" + PicDomain + $(this).data("pic-uri") + "'/>";
            }
        });
    });

    //初始化编辑网点地图
    bmap_edit_branch = new BMap.Map("ctn_edit_branch_bmap", {enableMapClick: false});          // 创建地图实例
    bmap_edit_branch.enableScrollWheelZoom();   //启用滚轮放大缩小，默认禁用
    bmap_edit_branch.enableContinuousZoom();    //启用地图惯性拖拽，默认禁用
    bmap_edit_branch.centerAndZoom("北京", 13);
    bmap_edit_branch.addEventListener("click", function (e) {
        bmap_edit_branch.clearOverlays();
        bmap_edit_branch.addOverlay(new BMap.Marker(e.point));
        form_edit_branch.geoPoint.value = e.point.lat + "," + e.point.lng;
    });
    //绑定定位事件
    var bmap_local_edit_branch = new BMap.LocalSearch(bmap_edit_branch, {renderOptions: {map: bmap_edit_branch}});
    $("#btn_edit_branch_mapmarker").click(function () {
        bmap_local_edit_branch.search(form_edit_branch.address.value);
    });

    //初始化新增网点地图
    bmap_new_branch = new BMap.Map("ctn_new_branch_bmap", {enableMapClick: false});          // 创建地图实例
    bmap_new_branch.enableScrollWheelZoom();   //启用滚轮放大缩小，默认禁用
    bmap_new_branch.enableContinuousZoom();    //启用地图惯性拖拽，默认禁用
    bmap_new_branch.centerAndZoom("北京", 13);
    bmap_new_branch.addEventListener("click", function (e) {
        bmap_new_branch.clearOverlays();
        bmap_new_branch.addOverlay(new BMap.Marker(e.point));
        form_new_branch.geoPoint.value = e.point.lat + "," + e.point.lng;
    });
    //绑定定位事件
    var bmap_local_new_branch = new BMap.LocalSearch(bmap_new_branch, {renderOptions: {map: bmap_new_branch}});
    $("#btn_new_branch_mapmarker").click(function () {
        bmap_local_new_branch.search(form_new_branch.address.value);
    });


    //录入网点
    $("[name='btn_save_new_branch']").click(function () {
        var name = form_new_branch.name.value;
        var linkMan = form_new_branch.linkMan.value;
        var linkPhone = form_new_branch.linkPhone.value;
        var departmentId = form_new_branch.departmentId.value;
        var address = form_new_branch.address.value;
        var geoPoint = form_new_branch.geoPoint.value;
        var remark = form_new_branch.remark.value;
        var state = form_new_branch.state.value;
        var pictures = "";
        $("#ctn_new_branch_pics img").each(function () {
            pictures += $(this).data("picuri") + ",";
        });

        var branch = {name: name, linkMan: linkMan, linkPhone: linkPhone, departmentId: departmentId, address: address, geoPoint: geoPoint, remark: remark, state: state, pictures: pictures};
        $.postJsonBody("/branch", branch, function (re) {
        	window.location.href=window.location.href; 
        	window.location.reload; 
        })
    });

    //编辑网点
    $("[name='btn_save_edit_branch']").click(function () {
        var id = form_edit_branch.id.value;
        var name = form_edit_branch.name.value;
        var linkMan = form_edit_branch.linkMan.value;
        var linkPhone = form_edit_branch.linkPhone.value;
        var departmentId = form_edit_branch.departmentId.value;
        var address = form_edit_branch.address.value;
        var geoPoint = form_edit_branch.geoPoint.value;
        var remark = form_edit_branch.remark.value;
        var state = form_edit_branch.state.value;
        var pictures = "";
        $("#ctn_edit_branch_pics img").each(function () {
            pictures += $(this).data("picuri") + ",";
        });
        var branch = {id: id, name: name, linkMan: linkMan, linkPhone: linkPhone, departmentId: departmentId, address: address, geoPoint: geoPoint, remark: remark, state: state, pictures: pictures};
        $.putJsonBody("/branch/" + id, branch, function (re) {
        	window.location.href=window.location.href; 
        	window.location.reload; 
        })
    });

    //删除网点
    $("[name='btn_delete_branch']").click(function () {
        var branchId = $(this).data("branch-id");
        bootbox.bconfirm("确定要删除这个网点吗？", function (re) {
            if (re) {
                $.delete("/branch/" + branchId, function (re) {
                    if (re.data) {
                        // tipper.success("删除成功，请刷新页面");
                    	window.location.href=window.location.href; 
                    	window.location.reload; 
                    } else {
                        tipper.danger("删除失败，请重试");
                    }
                });
            }
        });
    });


    //上传图片
    $("[name='btn_new_branch_upload_pic']").click(function () {
        var uploaded_count = $("#ctn_new_branch_pics").find("img").length;
        if (uploaded_count < 3) {
            $("#ipt_new_branch_upload_pic").click();
        } else {
            bootbox.balert("图片数量限制3张以内");
            return;
        }
    });
    $('#ipt_new_branch_upload_pic').fileupload({
        dataType: 'json',
        url: "/upload/pic?type=2",
        done: function (e, data) {
            var res = data.jqXHR.responseJSON;
            var $imgEle = $("<img src='" + PicDomain + res.data + "' data-picuri='" + res.data + "'/>");
            $imgEle.click(function () {
                $(this).remove();
            });
            $("#ctn_new_branch_pics").append($imgEle);
        }
    });

    $("[name='btn_edit_branch_upload_pic']").click(function () {
        var uploaded_count = $("#ctn_edit_branch_pics").find("img").length;
        if (uploaded_count < 3) {
            $("#ipt_edit_branch_upload_pic").click();
        } else {
            bootbox.balert("图片数量限制3张以内");
            return;
        }
    });
    $('#ipt_edit_branch_upload_pic').fileupload({
        dataType: 'json',
        url: "/upload/pic?type=2",
        done: function (e, data) {
            var res = data.jqXHR.responseJSON;
            var $imgEle = $("<img src='" + PicDomain + res.data + "' data-picuri='" + res.data + "'/>");
            $imgEle.click(function () {
                $(this).remove();
            });
            $("#ctn_edit_branch_pics").append($imgEle);
        }
    });


    //加载异步数据
    $.get("/department/list", function (re) {
        var departmentTree = re.data;
        var form = window.form_new_product;
        var opts_html = "";
        opts_html = departmentOptionMaker(departmentTree, 0);

        $(window.form_new_branch.departmentId).append(opts_html);
        $(window.form_edit_branch.departmentId).append(opts_html);
    });

});


// 网点详情
$('#md_edit_branch').on('show.bs.modal', function (event) {
    var form = window.form_edit_branch;
    //加载网点详情
    var _e = $(event.relatedTarget);
    var branchId = _e.data("branch-id");
    var modal = $(this);
    $.get("/branch/" + branchId, function (re) {
        var branch = re.data;
        form.id.value = branch.id;
        form.name.value = branch.name;
        form.linkMan.value = branch.linkMan;
        form.linkPhone.value = branch.linkPhone;
        form.address.value = branch.address;
        form.geoPoint.value = branch.geoPoint;
        form.remark.value = branch.remark;
        $(form.state).val(branch.state);
        $(form.departmentId).val(branch.departmentId);
        $("#ctn_edit_branch_pics").empty();
        if (branch.pictures) {
            var pictures = branch.pictures.split(",");
            for (var i in pictures) {
                var uri = pictures[i];
                if (/.+/.test(uri)) {
                    var $imgEle = $("<img src='" + PicDomain + uri + "' data-picuri='" + uri + "'/>");
                    $imgEle.click(function () {
                        $(this).remove();
                    });
                    $("#ctn_edit_branch_pics").append($imgEle);
                }
            }
        }

        bmap_edit_branch.clearOverlays();
        if (branch.geoPoint) {
            var lat_lng = branch.geoPoint.split(",");
            var point = new BMap.Point(Number(lat_lng[1]), Number(lat_lng[0]));
            window.setTimeout(function () {
                bmap_edit_branch.addOverlay(new BMap.Marker(point));
                bmap_edit_branch.panTo(point);
            }, 500);
        } else {
            window.setTimeout(function () {
                bmap_edit_branch.panTo(new BMap.Point(116.40396, 39.915108), {noAnimation: true});
            }, 500);
        }
    });
});


function departmentOptionMaker(departmentList, level) {
    var opts_html = "";
    for (var i in departmentList) {
        var department = departmentList[i];

        var prefix = "";
        for (i = 0; i < level; i++) {
            prefix += "&nbsp;&nbsp;&nbsp;&nbsp;";
        }
        prefix += prefix.length == 0 ? "" : "|-";
        opts_html += "<option value='" + department.id + "'>" + prefix + department.name + "</option>";
        if (department.children.length > 0) {
            opts_html += departmentOptionMaker(department.children, level + 1);
        }
    }
    return opts_html;
}

//数据导出
$("[name='btn_export']").click(function () {
    var keyword = $("[name='keyword']").val();
    var state = $("[name='state']").val();
   
    //有数据时才能导出
    if($("#resultTotal_hidden").val() != 0){
    	bootbox.bconfirm("确定是否导出？", function (re) {
            if (re) {
            	 var url="/branch/export?keyword="+keyword+"&state="+state;
                 window.open(url);
            }
        });
    }else{
    	bootbox.balert("没有数据，无法导出!");
    }
});